<?php
class SMS {
	public static $errcode;
	//@todo 此为通用发送手机短信验证码方法
    static function buildverify($targe,$newapi=false,$content=false) {
    	if(!$content){
    		$code = self::genrandcode();
    		$id = rand(10,99);
          $content = "您本次操作验证码为：{$code}。为了保护您的账户安全，请勿转发他人";
        	//写入session
       		session('smscode',md5($code));
        }
		//如果是特殊号码，则不进行次数限制
		if(!in_array($targe,C("NOLIMIT_SMS_MOBILE"))){
			//每个号码一小时内不准超过3次，一天不得超过5次
			$send_timesbyhour = S('send_timesbyhour_'.$targe)?S('send_timesbyhour_'.$targe):0;
			$send_timesbyday = S('send_timesbyday_'.$targe)?S('send_timesbyday_'.$targe):0;
			if ($send_timesbyhour >= C("MSG_CONF.SEND_TIMESBYHOUR") || $send_timesbyday >= C("MSG_CONF.SEND_TIMESBYDAY")) {
				self::$errcode = 10011;
				return false;
			}
			$send_timesbyhour++;
			$send_timesbyday++;
			//缓存1小时
			S('send_timesbyhour_'.$targe,$send_timesbyhour,3600);
			//缓存1天
			S('send_timesbyday_'.$targe,$send_timesbyday,3600*24);
		   //写入队列
		   //...
	   }
       //发送
       $send = self::send($targe,$content);
       //返回序号/false
       return $send===true?$id:false;
    }
    static function buildvoiceverify($targe,$content=false) {
      if(!$content){
        $code = self::genrandcode();
        $id = rand(10,99);
        $num_arr = array('0'=>'零','1'=>'一','2'=>'二','3'=>'三','4'=>'四','5'=>'五','6'=>'六','7'=>'七','8'=>'八','9'=>'九');
        //$code = (STRING)$code;
        $content = "您的语音验证码是：{$code},,,";
        /*for($i = 0;$i<strlen($code);$i++){
          $content .= $num_arr[$code[$i]].'、、';
        }*/
        $content = str_repeat($content,2);
        //写入session
        session('smscode',md5($code));
      }
        //每个号码一小时内不准超过3次，一天不得超过5次
        $send_timesbyhour = S('send_timesbyhour_voice_' . $targe) ? S('send_timesbyhour_voice_' . $targe) : 0;
        $send_timesbyday = S('send_timesbyday_voice_' . $targe) ? S('send_timesbyday_voice_' . $targe) : 0;
        if ($send_timesbyhour >= C("MSG_CONF.SEND_TIMESBYHOUR_VOICE") || $send_timesbyday >= C("MSG_CONF.SEND_TIMESBYDAY_VOICE")) {
            self::$errcode = 10012;
            return false;
        }
        $send_timesbyhour++;
        $send_timesbyday++;
        //缓存1小时
        S('send_timesbyhour_voice_' . $targe, $send_timesbyhour, 3600);
        //缓存1天
        S('send_timesbyday_voice_' . $targe, $send_timesbyday, 3600 * 24);
      //发送
      $send = self::sendvoice($targe,$content);
      //返回序号/false
      return $send===true?$id:false;
    }
    static function genrandcode(){
    	return rand(100000,999999);
    }
    static function gengateway(){
    	return 'http://'.C('SMS_GATE').':'.C('SMS_PORT').'/cgi-bin/sendsms?username='.C('SMS_USER').'&password='.C('SMS_PASS').'&msgtype=1';
    }
    static function send($to,$content,$api_target='dahantc'){
		if( $api_target == 'dataaim'){
			$api_target = 'dahantc';
		}
		$method = 'api_'.$api_target;
		if(!method_exists(SMS, $method)){
		  self::$errcode = '接口不存在';
		  return false;
		}
		//检测是否是手机黑名单用户，如果是则不进行发送，只入数据库
        if( SmsRecord::checkBlackist($to) == false ){
            $result = self::$method($to,$content);
        }else{
            $result = 1;
        }
		self::$errcode = $result;
		SmsRecord::add($to,$content,$result);
		//重复发送个锤子啊
		return true;
		//return $result==0?true:false;
    	return !$result?true:false;
    }
    static function sendvoice($to,$content){
        //检测是否是手机黑名单用户，如果是则不进行发送，只入数据库
        if( SmsRecord::checkBlackist($to) == false){
            $result = self::api_dahantc_voice($to,$content);
        }else{
            $result = 1;
        }
        self::$errcode = $result;
        SmsRecord::add($to,$content,$result);
        return !$result?true:false;
    }

    static function api_jianzhou($to,$content){
      $ws = "http://www.jianzhou.sh.cn/JianzhouSMSWSServer/services/BusinessService?wsdl";
      $client = new SoapClient($ws);
      $content = $content;
      $arr = array(
          'account'   =>  'sdk_jiedai',       //登录账号
          'password'    =>  '131276',       //密码
          'destmobile'  =>  $to,      //手机号，多个手机号用;分割
          'msgText'   =>  $content.'【旭胜股份】' //短信内容
          );
      $response = $client->sendBatchMessage($arr)->sendBatchMessageReturn;
      if(!$response){
          return '系统错误！';
      }
      if($response>0){
          return 0;
      }
      switch($response){
          case -1:
            $error = '余额不足';
            break;
          case -2:
            $error = '帐号或密码错误';
            break;
          case -3:
            $error = '连接服务商失败';
            break;
          case -4:
            $error = '超时';
            break;
          case -5;
            $error = '其他错误，一般为网络问题，IP受限等';
            break;
          case -6:
            $error = '短信内容为空';
            break;
          case -7:
            $error = '目标号码为空';
            break;
          case -8:
            $error = '用户通道设置不对，需要设置三个通道';
            break;
          case -9:
            $error = '捕获未知异常';
            break;
          case -10:
            $error = '超过最大定时时间限制';
            break;
          case -11:
            $error = '目标号码在黑名单里';
            break;
          case -12:
            $error = '消息内容包含禁用词语';
            break;
          case -13:
            $error = '没有权限使用该网关';
            break;
          case -14:
            $error = '找不到对应的Channel ID';
            break;
          case -17:
            $error = '没有提交权限，客户端帐号无法使用接口提交';
            break;
          case -20:
            $error = '超速提交(一般为每秒一次提交)';
            break;
          default:
            $error = '未知的错误类型:'.$response.'，请联系服务商QQ:736802753';
        }
        return $error;
    }
    static function api_jianzhou_voice($to,$content){
    //语音短信，10-20秒之间
      $ws = "http://www.jianzhou.sh.cn/JianzhouSMSWSServer/services/BusinessService?wsdl";
      $client = new SoapClient($ws);
      $arr = array(
          'account'   =>  'sdk_jiedai',   //登录账号
          'password'    =>  '131276',     //密码
          'sendDateTime'  =>  time(),       //定时日期
          'destmobile'  =>  $to,    //手机号，多个手机号用;分割
          'msgText'   =>  $content, //语音短信内容
          'srcMobile'   =>  ''          //源号码，留空
          );
      $response = $client->sendAudio($arr)->return;
      if(!$response){
        return '系统错误！';
      }
      if($response>0){
        return 0;
      }
      switch($response){
          case -1:
            $error = '余额不足';
            break;
          case -2:
            $error = '帐号或密码错误';
            break;
          case -3:
            $error = '连接服务商失败';
            break;
          case -4:
            $error = '超时';
            break;
          case -5;
            $error = '其他错误，一般为网络问题，IP受限等';
            break;
          case -6:
            $error = '短信内容为空';
            break;
          case -7:
            $error = '目标号码为空';
            break;
          case -8:
            $error = '用户通道设置不对，需要设置三个通道';
            break;
          case -9:
            $error = '捕获未知异常';
            break;
          case -10:
            $error = '超过最大定时时间限制';
            break;
          case -11:
            $error = '目标号码在黑名单里';
            break;
          case -12:
            $error = '消息内容包含禁用词语';
            break;
          case -13:
            $error = '没有权限使用该网关';
            break;
          case -14:
            $error = '找不到对应的Channel ID';
            break;
          case -17:
            $error = '没有提交权限，客户端帐号无法使用接口提交';
            break;
          case -20:
            $error = '超速提交(一般为每秒一次提交)';
            break;
          default:
            $error = '未知的错误类型:'.$response.'，请联系服务商QQ:736802753';
      }
      return $error;
    }
    //直达分众
    static function api_dataaim($to,$content){
      //账户基本信息
      $compCode = 'xsjr';
      $userName = 'admin';
      $password = '48B61EC826449C9179BC058B97D62AD6';
      $content = urlencode($content);
      $api_url = "http://www.10690071.com:9007/url_sms/struts/urlCurrentAction!toCurrentSms?userName={$userName}&compCode={$compCode}&pwd={$password}&message={$content}&phone={$to}";
      $res_msg = iconv('GBK','UTF-8//IGNORE',file_get_contents($api_url));
      $res = substr($res_msg,0,2);
      if(strtolower($res)=='ok'){
        return 0;
      }else{
        return $res_msg;
      }
    }
    //大汉三通
    static function api_dahantc($to,$content){
      //post数据
      $data = array(
                  'account'   => 'dh24941',                           //用户账号
                  'password'  => strtolower(md5('x3?yO8m7')),         //账号密码，需采用MD5加密(32位小写)；
                  'msgid'     => '',                                  //该批短信编号(32位UUID)，需保证唯一，选填；
                  'phones'    => $to,                                 //接收手机号码，多个手机号码用英文逗号分隔，最多500个
                  'content'   => $content,                            //短信内容，最多350个汉字
                  'sign'      => '【旭胜金融】',                       //短信签名
                  'subcode'   => '',                                  //短信签名对应子码(大汉三通提供)+自定义扩展子码(选填)，必须是数字，选填，未填使用签名对应子码
                  'sendtime'  => '',                                  //定时发送时间，格式yyyyMMddHHmm，为空或早于当前时间则立即发送；
                );
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL, "http://wt.3tong.net/json/sms/Submit");
      curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
      curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
      curl_setopt($ch, CURLOPT_HEADER, FALSE);
      curl_setopt($ch, CURLOPT_POST, TRUE);
      curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data) );
      $res = curl_exec( $ch );
      curl_close( $ch );
      $returndata = json_decode($res,true);
      return $returndata['result'];
    }
    //大汉三通（语音验证码）
    static function api_dahantc_voice($to,$content){
      $data = "message=<?xml version='1.0' encoding='UTF-8'?><message><account>dh24941</account><password>".strtolower(md5('x3?yO8m7'))."</password><data><voiceSms><phones>".$to."</phones><content>".$content."</content><msgId></msgId></voiceSms></data></message>";
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL, "http://voice.3tong.net/http/voiceSms/Submit");
      curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
      curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
      //curl_setopt($ch, CURLOPT_HEADER, $header);
      curl_setopt($ch, CURLOPT_POST, TRUE);
      curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
      $res = curl_exec( $ch );
      curl_close( $ch );
      $xml = simplexml_load_string($res);
      $returndata = (string)$xml->result;
      return $returndata;
    }
    //@todo 此为特殊发送手机短信验证码方法（非特殊情况不可调用）
    static function buildverifyNew($targe,$content,$newapi=false) {
        $code = self::genrandcode();
        $id = rand(10,99);
        $content = "您的短信验证码是{$code}。" . $content;
        //写入session
        session('smscode',md5($code));
        //如果是特殊号码，则不进行次数限制
        if(!in_array($targe,C("NOLIMIT_SMS_MOBILE"))){
            //每个号码一小时内不准超过3次，一天不得超过5次
            $send_timesbyhour = S('send_timesbyhour_'.$targe)?S('send_timesbyhour_'.$targe):0;
            $send_timesbyday = S('send_timesbyday_'.$targe)?S('send_timesbyday_'.$targe):0;
            if ($send_timesbyhour >= C("MSG_CONF.SEND_TIMESBYHOUR") || $send_timesbyday >= C("MSG_CONF.SEND_TIMESBYDAY")) {
                self::$errcode = 10011;
                return false;
            }
            $send_timesbyhour++;
            $send_timesbyday++;
            //缓存1小时
            S('send_timesbyhour_'.$targe,$send_timesbyhour,3600);
            //缓存1天
            S('send_timesbyday_'.$targe,$send_timesbyday,3600*24);
            //写入队列
            //...
        }
        //发送
        $send = self::send($targe,$content);
        //返回序号/false
        return $send===true?$id:false;
    }
}

//短信记录
class SmsRecord{
    /**
    * @brief add
    *
    * @param $mobile  接收人
    * @param $content 内容
    * @param $result 发送状态
    *
    * @return boolean
     */
	public static function add($mobile = 0, $content = '', $result = false){
		$data = array();
		$data['mobile']  = trim($mobile);
		$data['content'] = $content;
		$data['status']  = ($result === false) ? 0 : ( $result == 0 ? 1 : 0);
		M(C('JD_DB').'SmsRecord')->add($data);
	}

    /**
     * @brief add
     *
     * @param $mobile  接收人
     * @param $result  黑名单状态
     *
     * @return boolean
     */
    public static function checkBlackist($mobile){
        $data = array();
        $data['mobile']  = trim($mobile);
        $data['status']  = 1;
        $res = M(C('JD_DB').'SmsBlacklist')->where($data)->find();
        if($res){
            return true;
        }else{
            return false;
        }
    }
}
?>
